package com.zeekr.myroomtest

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.zeekr.myroomtest.databinding.ActivityMainBinding
import com.zeekr.myroomtest.room.Item
import java.util.Date
import java.util.Random

/**
 * 具体Room操作详见官方文档
 * https://developer.android.google.cn/codelabs/basic-android-kotlin-training-persisting-data-room?hl=zh-cn#0
 */
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    /*private val viewModel: InventoryViewModel by lazy {
        InventoryViewModel(
            (application as InventoryApplication).database.itemDao()
        )
    }*/
    private val viewModel: InventoryViewModel by lazy {
        ViewModelProvider(this).get(InventoryViewModel::class.java)
    }
    //private val viewModel by lazy { ViewModelProvider(this)[InventoryViewModel::class.java] }
    //private val viewModel: InventoryViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        binding.btnAdd.setOnClickListener {
            viewModel.insertItem(
                Item(
                    itemName = Date().toString(),
                    itemPrice = Random().nextDouble(),
                    quantityInStock = Random().nextInt(100)
                )
            )
        }

        binding.btnDel.setOnClickListener {
            viewModel.delete()
        }

        binding.btnDelAll.setOnClickListener {
            viewModel.deleteAll()
        }

        binding.btnQeuryAll.setOnClickListener {
            viewModel.queryAll()
        }

        binding.btnUpdate.setOnClickListener {
            if (viewModel.selectItem == null) {
                Toast.makeText(this@MainActivity, "selectItem不能为null", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val item = Item(viewModel.selectItem!!.id, "新的", 123.0, 99)
            viewModel.update(item)
        }
    }
}